package org.sufficientlysecure.htmltextview.glide;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v4.util.LruCache;

import java.util.Iterator;
import java.util.Map;

/**
 * Created by admin on 2017/7/29.
 */

public class DrawableCacheUtil {
    /**
     * 缓存Image的类，当存储Image的大小大于LruCache设定的值，系统自动释放内存
     */
    private LruCache<String, Drawable> mMemoryCache;
    private static DrawableCacheUtil bitmapCacheUtil;

    private DrawableCacheUtil() {
        //获取系统分配给每个应用程序的最大内存，每个应用系统分配32M
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int mCacheSize = maxMemory / 16;
        //给LruCache分配1/164M
        mMemoryCache = new LruCache<String, Drawable>(mCacheSize) {

            //必须重写此方法，来测量Drawable的大小
            @Override
            protected int sizeOf(String key, Drawable drawable) {
                if (drawable instanceof com.bumptech.glide.load.resource.gif.GifDrawable) {
                    return ((com.bumptech.glide.load.resource.gif.GifDrawable) drawable).getSize() / 1024;
                } else {
                    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                    return bitmap.getRowBytes() * bitmap.getHeight() / 1024;// KB
                }
            }

            @Override
            protected void entryRemoved(boolean evicted, String key, Drawable oldValue, Drawable newValue) {
                super.entryRemoved(evicted, key, oldValue, newValue);
                if (evicted && oldValue != null) {
                    oldValue.setCallback(null);
                }
            }
        };
    }

    public void remove(String key) {
        Drawable bitmap = mMemoryCache.remove(key);
        if (bitmap != null) {
            bitmap.setCallback(null);
        }
    }

    /**
     * 清空Drawable缓存
     */
    public void clearCache() {
        Map<String, Drawable> map = mMemoryCache.snapshot();
        Iterator<Map.Entry<String, Drawable>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Drawable> entry = iterator.next();
            remove(entry.getKey());
        }
//        mMemoryCache.trimToSize(0);//清除所有缓存
    }

    /**
     * 获取缓存工具类实例
     *
     * @return
     */
    public static DrawableCacheUtil getInstance() {
        if (bitmapCacheUtil == null) {
            bitmapCacheUtil = new DrawableCacheUtil();
        }
        return bitmapCacheUtil;
    }

    /**
     * 添加Drawable到内存缓存
     *
     * @param key
     * @param bitmap
     */
    public void put(String key, Drawable bitmap) {
        if (get(key) == null && bitmap != null) {
            mMemoryCache.put(key, bitmap);
        }
    }

    /**
     * 从内存缓存中获取一个Drawable
     *
     * @param key
     * @return
     */
    public Drawable get(String key) {
        return mMemoryCache.get(key);
    }
}
